<template>
	<view class="dish-management">
		<!-- 搜索和添加区域 -->
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" placeholder="输入名称" @confirm="handleSearch" @clear="handleSearchClear"
				cancelButton="none" style="flex: 1;" />
			<view class="category-select">
				<uni-data-select v-model="searchCategory" :localdata="categoryOptions" placeholder="全部分类" @change="handleSearch"
					style="width: 200rpx; margin-right: 10rpx;" />
			</view>
			<button class="add-btn" @click="showAddDialog">新增菜品</button>
		</view>

		<!-- 菜品列表 -->
		<view class="list-container">
			<view v-for="(dish,index) in filteredDishes" :key="dish._id" class="dish-card">
				<view class="card-left">
					<image class="dish-image" :src="dish.imageUrl" mode="aspectFill" @error="handleImageErr(dish)"></image>
					<view class="card-content">
						<view class="card-header">
							<text class="name"><text class="no">{{index+1}}</text>{{ dish.name }}</text>
							<text class="status" :class="{ 'status-disabled': dish.status === 0 }" @click="toggleStatus(dish)">
								{{ dish.status === 1 ? '已启售' : '已停售' }}
							</text>
						</view>
						<view class="card-body">
							<view class="info-item">
								<text class="price">¥{{ dish.price.toFixed(2) }}</text>
								<uni-icons type="settings" size="16"></uni-icons>
								<text class="category-name">{{ dish.categoryName }}</text>
							</view>
							<view class="info-item">
								<uni-icons type="info" size="16"></uni-icons>
								<text class="description">{{ dish.description || '暂无描述' }}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="card-right">
					<button class="action-btn edit-btn" @click="showEditDialog(dish)">修改</button>
					<button class="action-btn delete-btn" @click="confirmDelete(dish)">删除</button>
				</view>
			</view>

			<uni-load-more :status="loadStatus" @clickLoadMore="showMoreData"></uni-load-more>
			<view class="safe-area-box"></view>
		</view>

		<!-- 添加/编辑弹窗 -->
		<uni-popup ref="popup" type="dialog" style="z-index: 20;" :mask-click="false">
			<view class="popup-content">
				<view class="title-box">
					<text class="title-text">{{isEditMode?'修改菜品':'添加菜品'}}</text>
				</view>
				<view class="form-container">
					<uni-forms ref="form" :model="formData" :rules="rules">
						<uni-forms-item label="菜品名称" name="name" label-align="right">
							<uni-easyinput v-model="formData.name" placeholder="请输入菜品名称" />
						</uni-forms-item>
						<uni-forms-item label="菜品分类" name="categoryId" label-align="right">
							<uni-data-select v-model="formData.categoryId" :localdata="categoryOptions" placeholder="请选择分类" />
						</uni-forms-item>
						<uni-forms-item label="菜品价格" name="price" label-align="right">
							<uni-easyinput type="number" v-model.number="formData.price" placeholder="请输入价格" />
						</uni-forms-item>
						<uni-forms-item label="菜品图片" name="image" label-align="right">
							<view class="upload-container">
								<template v-if="formData.imageUrl">
									<image :src="formData.imageUrl" class="preview-image" mode="aspectFill" @click="chooseImage"
										@error="handleImageErr(formData)"></image>
								</template>
								<template v-else>
									<view class="image-placeholder" @click="chooseImage">
										<uni-icons type="plusempty" size="40" color="#999"></uni-icons>
									</view>
								</template>
							</view>
						</uni-forms-item>
						<uni-forms-item label="菜品描述" name="description" label-align="right">
							<uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入菜品描述" />
						</uni-forms-item>
						<uni-forms-item label="口味规格" name="flavors" label-align="right">
							<view class="flavors-container">
								<button class="add-flavor" :disabled="dishFlavorsData.length===dishFlavors.length" size="mini"
									type="primary" @click="onAddFlavor">添加口味</button>
								<view v-if="dishFlavors.length>0" class="select-flavor">
									<view v-for="(item,index) in dishFlavors" class="select-flavor-item" :key="index">
										<uni-data-select v-if="!dishFlavors[index].name" v-model="dishFlavors[index].name"
											:localdata="flavorsOptions" placeholder="请选择" class="select-flavor-item-name"
											@change="(name)=>onSelectFlavorName(name,index)" />
										<view v-else class="flavor-title">
											<text>{{dishFlavors[index].name}}</text>
											<uni-icons type="close" size="20" color="red" @click="onSelectFlavorName('',index)"></uni-icons>
										</view>
										<view class="flavor-detail" v-if="dishFlavors[index].value&&dishFlavors[index].value.length>0">
											<checkbox-group class="flavor-detail-group" @change="(e)=>onFlavorChange(e,index)">
												<label class="flavor-detail-label" v-for="(flavorItem,index1) in dishFlavors[index].value"
													:key="flavorItem+index1">
													<checkbox :value="flavorItem" checked="true" />{{flavorItem}}
												</label>
											</checkbox-group>
										</view>
									</view>
								</view>
							</view>
						</uni-forms-item>
					</uni-forms>
					<view style="height: 400rpx;"></view>
				</view>
				<view class="dialog-buttons">
					<button class="dialog-btn cancel-btn" @click="onCancelForm">取消</button>
					<button class="dialog-btn confirm-btn" @click="submitForm">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch,
		onUnmounted
	} from 'vue';
	import {
		addDish,
		deleteDish,
		getDishes,
		updateDish,
		getDishFlavors,
		updateDishStatus,
	} from '../api/dish';
	import {
		getCategories
	} from '../api/category';

	// 菜品数据
	const dishes = ref([]);
	const searchKeyword = ref('');
	const searchCategory = ref('');
	let page = 1;
	let pageSize = 8;
	const loadStatus = ref('more');

	// 分类选项
	const categoryOptions = ref([]);

	// 弹窗相关
	const popup = ref(null);
	const form = ref(null);
	const isEditMode = ref(false);
	const formData = ref({});

	// 口味数据
	const dishFlavorsData = ref([{
			name: '甜味',
			value: ['无糖', '少糖', '半糖', '多糖', '全糖']
		},
		{
			name: '温度',
			value: ['常温', '热饮', '去冰', '少冰', '多冰']
		},
		{
			name: '忌口',
			value: ['无', '不要葱', '不要蒜', '不要香菜', '全忌']
		},
		{
			name: '辣度',
			value: ['不辣', '微辣', '中辣', '重辣']
		}
	]);

	// // 当前选中的口味
	// const selectedFlavors = ref({});

	// 表单验证规则
	const rules = {
		name: {
			rules: [{
					required: true,
					errorMessage: '请输入菜品名称',
				},
				{
					minLength: 2,
					maxLength: 20,
					errorMessage: '菜品名称长度在2-20个字符之间'
				}
			]
		},
		categoryId: {
			rules: [{
				required: true,
				errorMessage: '请选择菜品分类'
			}]
		},
		price: {
			rules: [{
					required: true,
					errorMessage: '请输入菜品价格'
				},
				{
					format: 'number',
					minimum: 0.01,
					errorMessage: '价格必须大于0'
				}
			]
		},
		image: {
			rules: [{
				required: true,
				errorMessage: '请上传菜品图片'
			}]
		}
	};

	// 初始化加载分类数据
	onMounted(async () => {
		await loadCategories();
		getListData();
	});

	onUnmounted(() => {
		clearNewImageId()
	})

	// 加载分类数据
	const loadCategories = async () => {
		const res = await getCategories({
			type: 1
		});
		categoryOptions.value = res.map(item => ({
			value: item._id,
			text: item.name
		}));
	};

	// 获取列表数据
	const getListData = async (page1 = 0) => {
		if (page1) {
			loadStatus.value = 'more';
			dishes.value = [];
			page = page1;
		}
		if (loadStatus.value === 'loading') {
			return;
		}
		if (loadStatus.value === 'no-more') {
			uni.showToast({
				title: '没有更多数据了...',
				icon: 'none'
			});
			return;
		}

		loadStatus.value = 'loading';
		const res = await getDishes({
			keyword: searchKeyword.value.trim(),
			categoryId: searchCategory.value,
			page,
			pageSize
		});

		if (res && res.length > 0) {
			dishes.value.splice(dishes.value.length, 0, ...res);
			dishes.value.forEach(item => item.imageUrl = item.image)
		}

		if (!res || res.length < pageSize) {
			loadStatus.value = 'no-more';
		} else {
			loadStatus.value = 'more';
		}
	};

	// 触底刷新数据
	const showMoreData = () => {
		if (loadStatus.value === 'more') {
			page++;
			getListData();
		}
	};

	// 计算属性：过滤后的菜品列表
	const filteredDishes = computed(() => {
		if (!searchKeyword.value && !searchCategory.value) {
			return dishes.value;
		}

		return dishes.value.filter(dish => {
			const nameMatch = searchKeyword.value.trim() ?
				dish.name.toLowerCase().includes(searchKeyword.value.trim().toLowerCase()) : true;
			const categoryMatch = searchCategory.value ?
				dish.categoryId === searchCategory.value : true;
			return nameMatch && categoryMatch;
		});
	});

	const handleImageErr = async (dish) => {
		if (dish.image) {
			const res = await wx.cloud.getTempFileURL({
				fileList: [dish.image]
			});
			dish.imageUrl = res.fileList[0].tempFileURL;
		} else {
			dish.imageUrl = '';
		}
		console.log('获取临时图片地址：', dish.imageUrl);
	}

	// 搜索菜品
	const handleSearch = () => {
		getListData(1);
	};

	// 清空搜索
	const handleSearchClear = () => {
		searchKeyword.value = '';
		getListData(1);
	};

	let oldImageId = ''
	let newImageId = ''
	const clearNewImageId = () => {
		if (newImageId) {
			wx.cloud.deleteFile({
				fileList: [newImageId]
			})
		}
		newImageId = ''
	}
	// 选择图片
	const chooseImage = async () => {
		try {
			// 1. 选择图片（正确获取返回值）https://636c-cloud1-7gr3oipuf5fdfeeb-1321751177.tcb.qcloud.la/images/1743514339305-257.jpg?sign=0e712bfd44b172671b1303afae60372b&t=1743518262

			const chooseRes = await uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
			});

			const tempFilePath = chooseRes.tempFilePaths[0];

			// 2. 上传到云存储
			const cloudFileName = `images/${Date.now()}-${Math.floor(Math.random() * 1000)}.jpg`;
			const uploadRes = await wx.cloud.uploadFile({
				filePath: tempFilePath,
				cloudPath: cloudFileName,
			});

			clearNewImageId()
			newImageId = uploadRes.fileID
			formData.value.image = uploadRes.fileID
			formData.value.imageUrl = uploadRes.fileID

			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
		} catch (err) {
			console.error('上传失败:', err);
			uni.showToast({
				title: '上传失败',
				icon: 'none'
			});
		}
	};

	const userInfo = wx.getStorageSync('userInfo') || {}
	const dishFlavors = ref([])

	// 显示添加弹窗
	const showAddDialog = async () => {
		oldImageId = ''
		clearNewImageId()
		dishFlavors.value = []
		isEditMode.value = false;
		formData.value = {
			name: '',
			categoryId: '',
			categoryName: '',
			price: 0,
			image: '',
			imageUrl: '',
			description: '',
			status: 0,
			createUser: userInfo.empId,
			updateUser: userInfo.empId
		};
		popup.value.open();
	};

	let dishItem = {};
	let dishFlavorsTemp = JSON.stringify([])
	// 显示编辑弹窗
	const showEditDialog = async (dish) => {
		oldImageId = dish.image
		clearNewImageId()
		dishItem = dish;
		isEditMode.value = true;
		formData.value = {
			_id: dish._id,
			name: dish.name,
			categoryId: dish.categoryId,
			categoryName: dish.categoryName,
			price: dish.price,
			image: dish.image,
			imageUrl: dish.imageUrl,
			description: dish.description,
			status: dish.status,
			updateUser: userInfo.empId
		};

		// 加载口味数据
		const flavorsRes = await getDishFlavors(dish._id);
		if (flavorsRes && flavorsRes.length > 0) {
			dishFlavors.value = flavorsRes.map(item => ({
				name: item.name,
				value: JSON.parse(item.value)
			}));
			dishFlavorsTemp = JSON.stringify(dishFlavors.value)
		} else {
			dishFlavors.value = []
		}

		popup.value.open();
	};

	const flavorsOptions = computed(() => {
		const result = dishFlavorsData.value.map(item => ({
			value: item.name,
			text: item.name,
			disable: false
		}))
		const names = dishFlavors.value.map(e => e.name).filter(e => e)
		result.forEach(item => {
			if (names.includes(item.value)) item.disable = true
		})
		return result
	})

	const onAddFlavor = () => {
		dishFlavors.value.push({})
	}

	const onSelectFlavorName = (name, index) => {
		if (name) {
			dishFlavors.value[index].name = name
			dishFlavors.value[index].value = dishFlavorsData.value.find(e => e.name === name).value
		} else {
			dishFlavors.value.splice(index, 1)
		}
	}

	const onFlavorChange = (e, index) => {
		dishFlavors.value[index].value = e.detail.value
	}

	// 提交表单
	const submitForm = async () => {

		try {
			await form.value.validate();
			formData.value.categoryName = categoryOptions.value.find(item => item.value === formData.value.categoryId).text
			dishFlavors.value.filter(item => item.value && item.value.length !== 0)
			if (!formData.value.image) {
				wx.showToast({
					title: '请添加图片',
					icon: 'error'
				})
				return
			}
			delete formData.value.imageUrl
			if (isEditMode.value) {

				if (JSON.stringify(dishFlavors.value) !== dishFlavorsTemp) {
					formData.value.dishFlavors = dishFlavors.value
				}
				// 更新菜品
				await updateDish(formData.value);
				// 更新本地数据
				Object.assign(dishItem, formData.value);
				dishItem.imageUrl = dishItem.image
				uni.showToast({
					title: '修改成功',
					icon: 'success'
				});
			} else {
				formData.value.dishFlavors = dishFlavors.value
				// 添加菜品
				const res = await addDish(formData.value);

				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
				getListData(1);
			}
			if (newImageId && oldImageId) {
				wx.cloud.deleteFile({
					fileList: [oldImageId]
				});
			}
			newImageId = '';
			oldImageId = ''
			popup.value.close();
			console.log("提交数据 ：", formData.value);
		} catch (error) {
			console.error('提交失败:', error);
		}
	};

	const onCancelForm = () => {
		clearNewImageId()
		oldImageId = ''
		popup.value.close()
	}



	// 切换菜品状态
	const toggleStatus = async (dish) => {
		await updateDishStatus({
			_id: dish._id,
			status: dish.status === 1 ? 0 : 1
		});
		dish.status = dish.status === 1 ? 0 : 1;
		uni.showToast({
			title: dish.status === 1 ? '已起售' : '已停售，相关的套餐也已停售',
			icon: 'success'
		});
	};

	// 删除菜品
	const confirmDelete = async (dish) => {
		if (dish.status === 1) {
			wx.showToast({
				title: '起售状态，不能删除',
				icon: 'none'
			})
			return
		}
		const res = await uni.showModal({
			title: '提示',
			content: '确定要删除该菜品吗？',
		});
		if (res.cancel) {
			return;
		}
		await deleteDish(dish._id, dish.image);
		getListData(1);
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
	}

	defineExpose({
		showMoreData,
		getListData
	});
</script>

<style lang="scss" scoped>
	.dish-management {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx 20rpx 20rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
		width: 100%;
		height: 150rpx;
		position: fixed;
		top: 80rpx;
		left: 0;
		z-index: 5;

		.category-select {
			display: flex;
			flex-direction: column;
			justify-content: center;
			height: 100%;
			width: 220rpx;
		}

		.add-btn {
			margin-left: 5rpx;
			font-size: 28rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background-color: #ff5a5f;
			color: white;
			font-weight: 700;
		}
	}

	.list-container {
		flex: 1;
		padding: 20rpx;
		margin-top: 225rpx;
	}

	.dish-card {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx 20rpx 10rpx;
		margin-bottom: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

		.card-left {
			display: flex;
			width: 85%;

			.dish-image {
				width: 135rpx;
				height: 135rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}

			.card-content {
				flex: 1;
				max-width: 420rpx;

				.card-header {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;

					.name {
						font-size: 32rpx;
						font-weight: bold;
						margin-right: 16rpx;

						.no {
							display: inline-flex;
							font-size: 28rpx;
							width: 40rpx;
							border-radius: 25rpx;
							justify-content: center;
							align-items: center;
							color: #fa8c16;
							line-height: 100%;
						}
					}

					.status {
						padding: 2rpx 4rpx;
						border-radius: 4rpx;
						font-size: 24rpx;
						background-color: #52c41a;
						color: #fff;

						&.status-disabled {
							background-color: #fa8c16;
							color: #fff;
						}
					}
				}

				.card-body {
					display: flex;
					flex-direction: column;
					justify-content: space-evenly;

					.info-item {
						display: flex;
						align-items: center;
						margin-bottom: 12rpx;
						font-size: 26rpx;
						color: #666;

						.price {
							font-size: 28rpx;
							color: #ff4d4f;
							font-weight: bold;
							width: 140rpx;
							margin-left: 10rpx;
						}

						.category-name {
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							max-width: 225rpx;

						}


						uni-icons {
							margin-right: 8rpx;
							color: #999;
						}

						.description {
							color: #999;
							font-size: 24rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							max-width: 465rpx;
						}
					}
				}
			}
		}

		.card-right {
			width: 15%;
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;
			align-items: flex-end;

			.action-btn {
				// margin: 4rpx 0;
				margin-bottom: 10rpx;
				font-size: 26rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 8rpx;
				padding: 0 20rpx;

				&.edit-btn {
					background-color: #eee;
					color: #999;
				}

				&.delete-btn {
					background-color: #ff5a5f;
					color: white;
					font-weight: 700;
				}
			}
		}
	}

	.safe-area-box {
		height: env(safe-area-inset-bottom);
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		background-color: #fff;
		width: 90vw;
		border-radius: 20rpx;
		height: 80vh;
		z-index: 10;

		.title-box {
			box-sizing: border-box;
			display: flex;
			width: 100%;
			justify-content: center;
			padding: 30rpx 0;
			background-color: #f5f5f5;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
			border-radius: 20rpx 20rpx 0 0;

			.title-text {
				font-size: 40rpx;
				font-weight: 700;
				color: #666;
			}
		}

		.form-container {
			flex: 1;
			padding: 50rpx;
			overflow-y: auto;
			max-height: 60vh;
			box-sizing: border-box;

			.upload-container {
				display: flex;
				align-items: center;

				.preview-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}

				.image-placeholder {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
					border: 1px dashed #ccc;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #f9f9f9;
				}

				.upload-btn {
					font-size: 26rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 8rpx;
					padding: 0 20rpx;
					background-color: #eee;
					color: #666;
				}
			}

			.flavors-container {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				gap: 30rpx;

				.add-flavor {
					background-color: #ff5a5f;
					margin: 0;
				}

				.select-flavor {
					width: 100%;
					display: flex;
					flex-direction: column;
					gap: 30rpx;

					.select-flavor-item {
						box-sizing: border-box;
						padding: 20rpx;
						width: 100%;
						background-color: #eee;
						border-radius: 10rpx;
						box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);

						.select-flavor-item-name {
							display: inline-flex;
							width: 150rpx;
						}

						.flavor-title {
							display: flex;
							flex-direction: row;
							align-items: center;
							width: 150rpx;
							height: 60rpx;

							text {
								margin-right: 10rpx;
							}
						}

						.flavor-detail {
							margin-top: 20rpx;

							.flavor-detail-group {
								display: flex;
								flex-direction: row;
								width: 100%;
								gap: 10rpx;
								row-gap: 20rpx;
								flex-wrap: wrap;

								.flavor-detail-label {
									// 	margin-right: 10rpx;
									// 	margin-bottom: 20rpx;
								}
							}
						}
					}
				}
			}
		}

		.dialog-buttons {
			display: flex;
			justify-content: space-between;
			// margin-top: 40rpx;
			padding: 30rpx;
			background-color: #f5f5f5;
			border-radius: 0 0 20rpx 20rpx;
			box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.3);

			.dialog-btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				font-size: 28rpx;

				&.cancel-btn {
					background-color: #eee;
					color: #999;
					margin-right: 20rpx;
				}

				&.confirm-btn {
					background-color: #ff5a5f;
					color: white;
					font-weight: 700;
				}
			}
		}
	}
</style>